package com.simen.hellobytes.encrypt;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author Created by Simen.
 * @date 创建日期 2018/9/25 07:59
 * @modify 修改者 Simen
 */
public class KeyStoreUtil {

    /**
     * @param keyStorePath 密钥库文件路径(jks,keystore)
     * @param password
     * @return
     */
    public static KeyStore getKeyStore(String keyStorePath, String password) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

        FileInputStream is = new FileInputStream(keyStorePath);

        ks.load(is, password.toCharArray());

        is.close();

        return ks;
    }

    public static PrivateKey getPrivateKey(KeyStore keyStore, String alias, String password) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
        return (PrivateKey) keyStore.getKey(alias, password.toCharArray());
    }

    /**
     * 从密钥库中获得签名算法
     * (获取签名算法后,可以通过私钥进行签名操作,示例如下:)
     *
     * @param ks
     * @param alias
     * @return
     */
    public static Signature getSignature(KeyStore ks, String alias) throws KeyStoreException, NoSuchAlgorithmException {
        //获得证书
        X509Certificate x509Certificate = (X509Certificate) ks.getCertificate(alias);
        //构建签名,由证书指定签名算法
        return Signature.getInstance(x509Certificate.getSigAlgName());
    }

}
